<template>
  <div>
    <el-form
      ref="searchRef"
      :model="searchForm"
      :inline="true"
    >
      <el-form-item>
        <el-input
          v-model="searchForm.name"
          placeholder="请输入关键字搜索"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="Search"
          @click="onSearch(searchRef)"
        >
          搜索
        </el-button>
        <el-button
          type="primary"
          icon="Plus"
          @click="openAdd(formRef)"
        >
          添加
        </el-button>
      </el-form-item>
    </el-form>
    <el-main class="ea-table">
      <el-table
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column
          prop="keyword"
          label="关键字"
          width="150"
          align="center"
        />
        <el-table-column
          prop="type"
          label="事件类型"
          width="150"
          align="center"
        >
          <template #default="scope">
            {{ typeMap[scope.row.type] || '-' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="factor"
          label="场景"
          width="120"
          align="center"
        >
          <template #default="scope">
            {{ factorMap[scope.row.factor] || '-' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="content"
          label="回复内容"
          align="center"
        />
        <el-table-column
          prop="remark"
          label="描述"
          width="150"
          align="center"
        />
        <el-table-column
          prop="status"
          label="状态"
          width="120"
          align="center"
        >
          <template #default="scope">
            {{ scope.row.status ? '启用' : '停用' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="操作"
          fixed="right"
          width="150"
          align="center"
        >
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="openEdit(scope.row)"
            >
              修改
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="onDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <div class="page">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :background="true"
        layout="prev, pager, next, jumper"
        :total="pageTotal"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>

  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '修改' : '添加'"
    width="500"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="90"
    >
      <el-form-item
        label="关键词:"
        prop="keyword"
      >
        <el-input
          v-model="formData.keyword"
          placeholder="请输入"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item
        label="事件类型:"
        prop="type"
      >
        <el-select
          v-model="formData.type"
          placeholder="请选择"
        >
          <el-option
            v-for="(item, index) in typeMap"
            :key="index"
            :label="item"
            :value="index"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="formData.type === 0"
        label="回复内容:"
        prop="content"
      >
        <el-input
          v-model="formData.content"
          placeholder="请输入"
          type="textarea"
          :autosize="{ minRows: 4 }"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item
        label="选择场景:"
        prop="factor"
      >
        <el-radio-group v-model="formData.factor">
          <el-radio
            v-for="(item, index) in factorMap"
            :key="index"
            :value="index"
          >
            {{ item }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="formData.factor === 2"
        label="选择群聊:"
        prop="roomId"
      >
        <el-select
          v-model="formData.roomId"
          placeholder="请选择"
        >
          <el-option
            v-for="item in roomList"
            :key="item.id"
            :label="item.topic"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="状态:"
        prop="status"
      >
        <el-radio-group v-model="formData.status">
          <el-radio :value="0">
            停用
          </el-radio>
          <el-radio :value="1">
            启用
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="备注:"
        prop="remark"
      >
        <el-input
          v-model="formData.remark"
          placeholder="请输入"
          autocomplete="off"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          type="primary"
          @click="editConfirm(formRef)"
        >
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="js">
import { userStore } from '@/stores'
import { nextTick, onMounted, reactive, ref, toRaw } from 'vue'
import { getList, addReply, editReply, deleteReply } from '@/apis/autoresponse'
import { getGroupList } from '@/apis/mygroup'
import { ElMessageBox, ElNotification } from 'element-plus'

const user = userStore()

const searchForm = reactive({
  name: ''
})
const searchRef = ref()
const searchVal = ref()
const tableData = ref([])
const currentRow = ref({})
const roomList = ref([])

const currentPage = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)

const isEdit = ref(false)
const dialogVisible = ref(false)
const formRef = ref()
const formData = reactive({
  content: '',
  factor: 0,
  keyword: '',
  remark: '',
  robotId: user.robotId,
  roomId: null,
  status: 0,
  type: 0
})
const rules = reactive({
  keyword: [{ required: true, message: '请输入', trigger: 'blur' }],
  type: [{ required: true, message: '请选择', trigger: 'blur' }],
  factor: [{ required: true, message: '请选择', trigger: 'blur' }],
  roomId: [{ required: true, message: '请选择', trigger: 'blur' }]
})

// 事件类型
const typeMap = ['普通消息', '发送群邀请', '踢人指令']
// 场景
const factorMap = ['通用', '私聊', '群聊', '通用群聊']

onMounted(() => {
  fetchList()
  fetchGroupList()
})

function fetchList () {
  if (user.robotId) {
    getList({ search$$robotId$$: user.robotId }).then(res => {
      tableData.value = res.data.list || []
      pageTotal.value = res.data.total
    })
  }
}

function fetchGroupList () {
  getGroupList({ id: user.robotId }).then(res => {
    roomList.value = res.data || []
  })
}

const onSearch = (formEl) => {
  if (!formEl) return
  const params = {
    search$$robotId$$: user.robotId
  }
  formEl.validate((valid) => {
    if (valid) {
      const val = searchForm.name
      if (val) {
        params.search$$keyword$$all = val
        searchVal.value = val
      }
      getList(params).then(res => {
        tableData.value = res.data.list || []
        pageTotal.value = res.data.total
      })
    }
  })
}

const handleCurrentChange = (val) => {
  const params = {
    search$$robotId$$: user.robotId,
    search$$keyword$$all: searchVal.value,
    page: val
  }
  getList(params).then(res => {
    tableData.value = res.data.list || []
    pageTotal.value = res.data.total
  })
}

const openAdd = () => {
  isEdit.value = false
  dialogVisible.value = true
  currentRow.value = {}
  formData.content = ''
  formData.roomId = null
  nextTick(() => {
    formRef.value.resetFields()
  })
}
const openEdit = (row) => {
  isEdit.value = true
  dialogVisible.value = true
  currentRow.value = row

  formData.content = row.content
  formData.factor = row.factor
  formData.keyword = row.keyword
  formData.remark = row.remark
  formData.robotId = row.robotId
  formData.roomId = row.roomId
  formData.status = row.status
  formData.type = row.type
}
const onDelete = (row) => {
  ElMessageBox.confirm(
    '该操作数据不可逆，请谨慎操作!!!',
    '确定进行该操作吗？',
    {
      confirmButtonText: '确认',
      cancelButtonText: '我再想想',
      type: 'warning'
    }
  ).then(() => {
    deleteReply({ ids: [row._id] }).then(res => {
      res.success && fetchList()
    })
  })
}
const submitValidate = () => {
  if (formData.type === 1 && formData.factor !== 1) {
    ElNotification({
      title: '提示',
      message: '群邀请仅限私聊',
      type: 'warning'
    })
    return false
  }
  if (formData.type === 2 && (formData.factor === 0 || formData.factor === 1)) {
    ElNotification({
      title: '提示',
      message: '踢人仅限群聊和通用群聊',
      type: 'warning'
    })
    return false
  }
  return true
}
const editConfirm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      if (!submitValidate()) return
      if (isEdit.value) {
        if (!currentRow.value._id) return
        editReply(
          currentRow.value._id,
          toRaw(formData)
        ).then(res => {
          dialogVisible.value = false
          res.success && fetchList()
        })
      } else {
        addReply(toRaw(formData)).then(res => {
          dialogVisible.value = false
          res.success && fetchList()
        })
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.page{
  background: #FFFFFF;
  padding: 0px 10px 10px 10px;
  display: flex;
  justify-content: flex-end;
}
</style>
